package com.jinkeen.dddk

import ACTION_ALARM_REPLENISH_STOCK
import ACTION_ALARM_SYNCHRONIZE
import ALARM_REPLENISH_STOCK_CODE
import ALARM_SYNCHRONIZE_CODE
import android.app.AlarmManager
import android.app.Application
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import java.util.*
import kotlin.properties.Delegates

/**
 * @description: TODO
 * @author whz
 * @date 2021/12/29 15:22
 * @version 1.0
 */

class AlarmApplication : Application() {
    companion object {
        //自定义委托实现单例
        var instance: AlarmApplication by Delegates.notNull()
    }

    override fun onCreate() {
        super.onCreate()
        instance = this

        //启动定时任务
        startAlarm()
    }

    private fun startAlarm() {
        val hourMinuteArray = "17:40".split(":")
        //启动定时任务
        setAlarm(
            AlarmManager.RTC_WAKEUP, hourMinuteArray[0].toInt(), hourMinuteArray[1].toInt(),
            AlarmManager.INTERVAL_DAY, ALARM_REPLENISH_STOCK_CODE, ACTION_ALARM_REPLENISH_STOCK
        )
        //启动定时同步任务
        setAlarm(
            AlarmManager.RTC_WAKEUP, hourMinuteArray[0].toInt(), hourMinuteArray[1].toInt(),
            AlarmManager.INTERVAL_DAY, ALARM_SYNCHRONIZE_CODE, ACTION_ALARM_SYNCHRONIZE
        )

    }

    //取消闹钟
    private fun cancelAlarm(requestCode: Int, action: String) {
        val alarmManager: AlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager

        alarmManager.cancel(
            PendingIntent.getBroadcast(
                this,
                requestCode,
                Intent(action),
                PendingIntent.FLAG_UPDATE_CURRENT
            )
        )
    }

    private fun setAlarm(type: Int, hour: Int, minute: Int, intervalMillis: Long, requestCode: Int, action: String){
        val now=Calendar.getInstance()
        val targetTime=now.clone() as Calendar
        targetTime.set(Calendar.HOUR_OF_DAY,hour)
        targetTime.set(Calendar.MINUTE,minute)
        targetTime.set(Calendar.SECOND,0)
        targetTime.set(Calendar.MILLISECOND,0)
        if (targetTime.before(now)){
            targetTime.add(Calendar.DATE,1)
            //
            setAlarm(type,targetTime.timeInMillis,intervalMillis,requestCode,action)
        }
    }

    private fun setAlarm(type: Int, triggerAtMillis: Long, intervalMillis: Long, requestCode: Int, action: String){
        val alarmManager:AlarmManager=getSystemService(Context.ALARM_SERVICE) as AlarmManager
        alarmManager.setRepeating(type,triggerAtMillis,intervalMillis,PendingIntent.getBroadcast(this,requestCode,
            Intent(action),PendingIntent.FLAG_UPDATE_CURRENT
        ))
    }
}